package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;


@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中文乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //将请求数据风封装到user对象中传递给业务层的方法
        int result = new UserService().registerUser(new User(null, request.getParameter("username"), request.getParameter("password")));
        //判断结果
        PrintWriter pw = response.getWriter();
        if (result == 0) {
            pw.println("<script>");
            pw.println("alert('用户名密码不能为空!请重新输入!');");
            pw.println("location.href='http://localhost:8080/register.html';");
            pw.println("</script>");
        } else if (result == 1) {
            pw.println("<h1>注册成功</h1>");
            response.setHeader("refresh", "2;url=http://localhost:8080/login.html");
        } else if (result == 2) {
            pw.println("<script>");
            pw.println("alert('抱歉!该用户已被注册!');");
            pw.println("location.href='http://localhost:8080/register.html';");
            pw.println("</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}